<template>
  <div class="edit-container">
    <el-page-header :content="docId ? '编辑文档' : '新建文档'" @back="goBack" />

    <el-form :model="form" label-width="80px" class="edit-form">
      <el-form-item label="文档标题" prop="title" required>
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="文档内容" prop="content" required>
        <div class="editor-container">
          <WangEditor v-model:value="form.content" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="saveDocument" :loading="saveLoading">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import WangEditor from "@/components/WangEditor/index.vue";
import { getDocTreeApi, addDocNodeApi, updateDocNodeApi } from "@/api/modules/doc";
import { useUserStore } from "@/stores/modules/user";
import { useDocumentStore } from "@/stores/modules/document";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const documentStore = useDocumentStore();

const docId = ref<string>((route.query.id as string) || "");
const saveLoading = ref<boolean>(false);
const currentUserId = ref<string>(userStore.userInfo.FUserId || "");
const form = ref({
  title: "",
  content: ""
});

// 扁平化工具
function flattenTree(list: any[], result: any[] = []) {
  list.forEach(item => {
    result.push(item);
    if (item.children && item.children.length > 0) {
      flattenTree(item.children, result);
    }
  });
  return result;
}

// 加载文档数据（如果是编辑）
const loadDocument = async () => {
  if (!docId.value) return;
  try {
    const { data } = await getDocTreeApi({ FSpaceId: route.query.spaceId as string });
    const flatList = flattenTree(data);
    const currentDoc = flatList.find((item: any) => item.FId === docId.value);
    if (currentDoc) {
      form.value.title = currentDoc.FTitle || "";
      form.value.content = currentDoc.FContent || "";
    } else {
      ElMessage.warning("未找到对应文档");
    }
  } catch {
    ElMessage.error("加载文档失败");
  }
};

// 保存文档
const saveDocument = async () => {
  if (!form.value.title.trim()) {
    ElMessage.warning("请输入文档标题");
    return;
  }
  if (!form.value.content.trim()) {
    ElMessage.warning("请输入文档内容");
    return;
  }

  try {
    saveLoading.value = true;

    if (docId.value) {
      // 更新文档
      await updateDocNodeApi({
        FId: docId.value,
        FTitle: form.value.title,
        FContent: form.value.content,
        isAdmin: documentStore.isAdmin
      });

      // ✅ 刷新节点
      await documentStore.loadDocTree(documentStore.currentSpace!.FId);

      ElMessage.success("文档更新成功");
    } else {
      // 新建文档
      const { data } = await addDocNodeApi({
        FTitle: form.value.title,
        FContent: form.value.content,
        FParentId: (route.query.parentId as string) || "",
        FSpaceId: (route.query.spaceId as string) || "",
        FType: "doc",
        FAuthorId: currentUserId.value
      });

      docId.value = data.FId;

      // 刷新节点
      await documentStore.loadDocTree(documentStore.currentSpace!.FId);

      ElMessage.success("文档创建成功");
    }

    setTimeout(() => {
      goBack();
    }, 1000);
  } catch (error) {
    ElMessage.error("保存失败");
  } finally {
    saveLoading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  loadDocument();
});
</script>

<style scoped>
.edit-container {
  display: flex;
  flex-direction: column;
  max-width: 1200px;
  height: 100vh;
  padding: 20px;
  margin: 0 auto;
}
.edit-form {
  display: flex;
  flex: 1;
  flex-direction: column;
  margin-top: 20px;
}
.editor-container {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-height: 0;
  margin-top: 10px;
}
</style>
